package com.fengjing.launcher.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.ScrollView;

/**
 * Created by admin on 2017/9/19.
 */

public class MenuScrollView extends ScrollView {
    int pos;
    private OnItemSelectListener onItemSelectListener;

    public MenuScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {

            if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
                if (pos < getChildCount1() - 1) {
                    pos++;
                    if (onItemSelectListener != null) {
                        onItemSelectListener.onSelect(this, pos);
                    }
                    smoothScrollBy(0, 128);
                }
                return true;
            } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
                if (pos > 0) {
                    pos--;
                    if (onItemSelectListener != null) {
                        onItemSelectListener.onSelect(this, pos);
                    }
                    smoothScrollBy(0, -128);
                }
                return true;
            }
        }else if (event.getAction() == KeyEvent.ACTION_DOWN){
            if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
                return true;
            } else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
                return true;
            }
        }

        return super.dispatchKeyEvent(event);

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return true;
    }

    public void setOnItemSelectListener(OnItemSelectListener onItemSelectListener) {
        this.onItemSelectListener = onItemSelectListener;
    }

    public interface OnItemSelectListener {
        void onSelect(MenuScrollView view, int p);
    }

    public int getSelectPosition() {
        return pos;
    }

    public int getChildCount1() {
        if (getChildCount() > 0) {
            ViewGroup viewGroup = (ViewGroup) getChildAt(0);
            return viewGroup.getChildCount();
        }
        return 0;
    }
}
